package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.HouseAdapper;
import com.dotstone.chipism.bean.Home;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.OnOperItemClickL;
import com.dotstone.chipism.listener.TabHouseListener;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.EditDeviceNameDialog;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.NormalListDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TabHouseActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private TextView mHouseTv;
	private ListView mHouseLv;
	private Button mHouseBtn;
	private HouseAdapper mAdapter;
	private List<Home> mHomes = new ArrayList<Home>();
	private String hid1;
	private String hid2;
	private String homename1;
	private String homename2;
	private SVProgressHUD mSVProgressHUD;
	private boolean changed1 = false;
	private boolean changed2 = false;
	public static TabHouseActivity tabHouseActivity;
	private TabHouseListener tabHouseListener;
	private NormalListDialog mNormalListDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private String[] option;
	private EditDeviceNameDialog mEditNameDialog;
	private NormalDialog mNormalDialog;
	public void setTabHouseListener(TabHouseListener tabHouseListener) {
		this.tabHouseListener = tabHouseListener;
	}

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.house_btn:
			Intent intent = new Intent(getApplicationContext(), AddHouseActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				String name = msg.obj.toString();
				if (name.equals(homename1)) {
					changed1 = true;
				}
				if (name.equals(homename2)) {
					changed2 = true;
				}
				if (changed1 && changed2) {
					Log.i("wmy", "请求房屋");
					DeviceManager.getInstance().clearDevice();
					DeviceManager.getInstance().clearHouse();
					DeviceManager.getInstance().clearRoom();
					DeviceManager.getInstance().clearOrder();
					getHouse((String) SPUtils.get(getApplicationContext(), "token", ""));
					// MainActivity.mainActivity.clearAllData();
					if (tabHouseListener != null) {
						tabHouseListener.tabFinish();
					}
				}
				break;
			case 1:
				if (mSVProgressHUD.isShowing()) {
					ToastShow.Show(getApplicationContext(), getString(R.string.tab_success));
					mSVProgressHUD.dismiss();
				}
				SocketManager.getInstance().clearSocket();
				initData();
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_tab_house;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		tabHouseActivity = this;
		mSVProgressHUD = new SVProgressHUD(TabHouseActivity.this);
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mHouseTv = $(R.id.house_tv);
		mHouseLv = $(R.id.house_lv);
		mHouseBtn = $(R.id.house_btn);
		boolVersion();
		mBackL.setOnClickListener(this);
		mHouseBtn.setOnClickListener(this);
		mHouseLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// TODO Auto-generated method stub
				// 正在切换
				Log.i("wmy", "短按");
				mSVProgressHUD.showWithStatus("正在切换");
				// 修改hid和homeName
				hid1 = DeviceManager.getInstance().hid;
				hid2 = mHomes.get(position).getHid();
				homename1 = DeviceManager.getInstance().getHomeName();
				homename2 = mHomes.get(position).getHomeName();
				// 修改家庭状态
				changeStatus(hid1, homename1, 9);
				changeStatus(hid2, homename2, 1);
				// 请求家庭状态
				// 改变界面
			}
		});
		mHouseLv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				Log.i("wmy", "长按");
				showOptionDialog(position);
				return true;
			}
		});
		mHouseTv.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				mEditNameDialog = new EditDeviceNameDialog(TabHouseActivity.this);
				mEditNameDialog.setDeviceName(mHouseTv.getText().toString());
				mEditNameDialog.setOnCancelOptionListener(new EditDeviceNameDialog.OnCancelOptionListener() {

					@Override
					public void cancel() {
						mEditNameDialog.dismiss();
					}
				});
				mEditNameDialog.setOnEnsureOptionListener(new EditDeviceNameDialog.OnEnsureOptionListener() {

					@Override
					public void ensure(String name) {
						boolean e = DeviceManager.getInstance().checkName(name);
						if (e) {
							ToastShow.Show(getApplicationContext(), getString(R.string.device_exists1));
							return;
						}
						if (name.isEmpty() || name.length() < 2 || name.length() > 10) {
							ToastShow.Show(getApplicationContext(), getString(R.string.device_name_not_vaild));
						} else {
							mEditNameDialog.dismiss();
							updateName(name);
						}
					}
				});
				mEditNameDialog.show();
				return true;
			}
		});
	}

	private void showOptionDialog(final int position) {
		option = new String[3];
		option[0] = "编辑该房屋";
		option[1] = "删除该房屋";
		option[2] = "取消";
		mNormalListDialog = new NormalListDialog(TabHouseActivity.this, option, mHomes.get(position).getHomeName());
		mNormalListDialog.title("请选择")//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalListDialog.setOnOperItemClickL(new OnOperItemClickL() {

			@Override
			public void onOperItemClick(AdapterView<?> parent, View view, int position1, long id) {
				// TODO Auto-generated method stub
				switch (position1) {
				case 0:
					// 弹出编辑框
					// editDevice(device, type);
					editHouse(position);
					mNormalListDialog.dismiss();
					break;
				case 1:
					// 删除房屋
					// deleteDevice(device, type);
					deleteHouse(position);
					mNormalListDialog.dismiss();
					break;
				case 2:
					mNormalListDialog.dismiss();
					break;

				default:
					break;
				}
			}
		});
	}

	private void deleteHouse(final int position) {
		mNormalDialog = new NormalDialog(TabHouseActivity.this);
		mNormalDialog.content("是否删除该房屋：" + mHomes.get(position).getHomeName() + "？").style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
					ToastShow.Show(getApplicationContext(), "没有网络");
					return;
				}
				RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
				params.setAsJsonContent(true);
				JSONObject obj = new JSONObject();
				try {
					obj.put("handleType", 3);
					obj.put("hid", mHomes.get(position).getHid());
					obj.put("homeName", mHomes.get(position).getHomeName());
					obj.put("status", "9");
					obj.put("key", "10000");
					obj.put("requestTime", "" + System.currentTimeMillis());
					obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
					Log.d("Tag", "delete home " + obj.toString());
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				params.setBodyContent(obj.toString());
				x.http().post(params, new Callback.CommonCallback<String>() {
					@Override
					public void onSuccess(String result) {
						Log.e("test", "delete home=" + result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							String resultCode = jsonObject.getString("resultCode");
							if (resultCode.equals("1")) {
								ToastShow.Show(getApplicationContext(), "删除成功");
								getHouse((String) SPUtils.get(getApplicationContext(), "token", ""));
							} else {
								throw new Exception();
							}
						} catch (Exception e) {
							e.printStackTrace();
							ToastShow.Show(getApplicationContext(), "删除失败，请稍后再试");
						}
					}

					@Override
					public void onCancelled(CancelledException arg0) {

					}

					@Override
					public void onError(Throwable arg0, boolean arg1) {

					}

					@Override
					public void onFinished() {

					}
				});
			}
		});
	}

	private void editHouse(final int position) {
		mEditNameDialog = new EditDeviceNameDialog(TabHouseActivity.this);
		mEditNameDialog.setDeviceName(mHomes.get(position).getHomeName());
		mEditNameDialog.setOnCancelOptionListener(new EditDeviceNameDialog.OnCancelOptionListener() {

			@Override
			public void cancel() {
				mEditNameDialog.dismiss();
			}
		});
		mEditNameDialog.setOnEnsureOptionListener(new EditDeviceNameDialog.OnEnsureOptionListener() {

			@Override
			public void ensure(String name) {
				boolean e = DeviceManager.getInstance().checkName(name);
				if (e) {
					ToastShow.Show(getApplicationContext(), getString(R.string.device_exists1));
					return;
				}
				if (name.isEmpty() || name.length() < 2 || name.length() > 10) {
					ToastShow.Show(getApplicationContext(), getString(R.string.device_name_not_vaild));
				} else {
					mEditNameDialog.dismiss();
					updateName(name, position);
				}
			}
		});
		mEditNameDialog.show();
	}
	
	private void updateName(final String name) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
				params.setAsJsonContent(true);
				JSONObject obj = new JSONObject();
				try {
					obj.put("handleType", 2);
					obj.put("hid", DeviceManager.getInstance().hid);
					obj.put("homeName", name);
					obj.put("status", "1");
					obj.put("key", "10000");
					obj.put("requestTime", "" + System.currentTimeMillis());
					obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
					Log.d("Tag", "delete home " + obj.toString());
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				params.setBodyContent(obj.toString());
				x.http().post(params, new Callback.CommonCallback<String>() {
					@Override
					public void onSuccess(String result) {
						// Log.e("wmy", "修改名字 = " + result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							String value = jsonObject.getString("resultCode");
							if (value.equals("1")) {
								getHouse((String) SPUtils.get(getApplicationContext(), "token", ""));
							} else {
								ToastShow.Show(TabHouseActivity.this, "修改失败，请重试");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onCancelled(CancelledException arg0) {

					}

					@Override
					public void onError(Throwable arg0, boolean arg1) {

					}

					@Override
					public void onFinished() {

					}
				});
			}
		}).start();
	}

	private void updateName(final String name, final int position) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
				params.setAsJsonContent(true);
				JSONObject obj = new JSONObject();
				try {
					obj.put("handleType", 2);
					obj.put("hid", mHomes.get(position).getHid());
					obj.put("homeName", name);
					obj.put("status", "9");
					obj.put("key", "10000");
					obj.put("requestTime", "" + System.currentTimeMillis());
					obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
					Log.d("Tag", "delete home " + obj.toString());
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				params.setBodyContent(obj.toString());
				x.http().post(params, new Callback.CommonCallback<String>() {
					@Override
					public void onSuccess(String result) {
						// Log.e("wmy", "修改名字 = " + result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							String value = jsonObject.getString("resultCode");
							if (value.equals("1")) {
								getHouse((String) SPUtils.get(getApplicationContext(), "token", ""));
							} else {
								ToastShow.Show(TabHouseActivity.this, "修改失败，请重试");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onCancelled(CancelledException arg0) {

					}

					@Override
					public void onError(Throwable arg0, boolean arg1) {

					}

					@Override
					public void onFinished() {

					}
				});
			}
		}).start();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		 initData();
		getAllHouse();
	}

	private void getAllHouse() {
		RequestParams params = new RequestParams(HttpURL.GET_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("token", SPUtils.get(getApplicationContext(), "token", ""));
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.e("test", "login obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					int resultCode = jsonObject.optInt("resultCode");
					if (resultCode == 1) {
						DeviceManager.getInstance().clearHouse();
						JSONArray ja = jsonObject.optJSONArray("data");
						for (int i = 0; i < ja.length(); i++) {
							String hid = ja.getJSONObject(i).getString("hid");
							String userId = ja.getJSONObject(i).getString("userId");
							String homeName = ja.getJSONObject(i).getString("homeName");
							int status = ja.getJSONObject(i).getInt("status");
							if (status == 1) {
								DeviceManager.getInstance().homeName = homeName;
								DeviceManager.getInstance().hid = hid;
							}
							Home home = new Home(hid, userId, homeName, status);
							DeviceManager.getInstance().addHome(home);
						}
						Message message = Message.obtain();
						message.what = 1;
						mHandler.sendMessage(message);
					} else {
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), errorMsg);
						Intent intent = new Intent(TabHouseActivity.this, LoginActivity.class);
						startActivity(intent);
						finish();
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
				// 清空所有本地数据，进入MainActivity
				SPUtils.clear(getApplicationContext());
				Intent intent = new Intent(TabHouseActivity.this, LoginActivity.class);
				startActivity(intent);
				finish();
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	private void initData() {
		// TODO Auto-generated method stub
		String name = DeviceManager.getInstance().getHomeName();
		mHouseTv.setText(name);
		mHomes = DeviceManager.getInstance().getHome();
		mAdapter = new HouseAdapper(getApplicationContext(), mHomes);
		mHouseLv.setAdapter(mAdapter);
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	private void changeStatus(String hid, final String name, int status) {
		if (NetUtil.isNetworkAvailable(this)) {
			RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			String token = (String) SPUtils.get(getApplicationContext(), "token", "");
			try {
				obj.put("hid", hid);
				obj.put("key", "10000");
				obj.put("homeName", name);
				obj.put("handleType", "2");
				obj.put("token", token);
				obj.put("status", status);
				obj.put("requestTime", "" + System.currentTimeMillis());
				Log.d("test", "login obj = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());

			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("Tag", "成功=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);

						int resultCode = jsonObject.optInt("resultCode");

						if (resultCode == 1) {
							Message msg = Message.obtain();
							msg.what = 0;
							msg.obj = name;
							mHandler.sendMessage(msg);

						} else {
							String errorMsg = jsonObject.getString("errorMsg");
							ToastShow.Show(TabHouseActivity.this, errorMsg);
							throw new Exception();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {
					Log.e("Tag", "错误" + ex.getMessage());
				}

				@Override
				public void onCancelled(CancelledException cex) {

				}

				@Override
				public void onFinished() {
					Log.e("Tag", "完成");
				}
			});
		} else {
			ToastShow.Show(getApplicationContext(), getString(R.string.nonetwork));
		}
	}

	private void getHouse(String token) {
		RequestParams params = new RequestParams(HttpURL.GET_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("token", token);
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "login obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");
					DeviceManager.getInstance().clearHouse();
					if (resultCode == 1) {
						JSONArray ja = jsonObject.optJSONArray("data");

						for (int i = 0; i < ja.length(); i++) {
							String hid = ja.getJSONObject(i).getString("hid");
							String userId = ja.getJSONObject(i).getString("userId");
							String homeName = ja.getJSONObject(i).getString("homeName");
							int status = ja.getJSONObject(i).getInt("status");
							if (status == 1) {
								DeviceManager.getInstance().homeName = homeName;
								DeviceManager.getInstance().hid = hid;
							}
							Home home = new Home(hid, userId, homeName, status);
							DeviceManager.getInstance().addHome(home);
						}
						Message msg = Message.obtain();
						msg.what = 1;
						mHandler.sendMessage(msg);

					} else {
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(TabHouseActivity.this, errorMsg);

						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}
}
